console.log('[shopReport] 加载插件')

// 当前页
var current = 1
// 是否已经设置点击动作
var isSetClicked = false
// 计时器
var timer = null
// 心跳时间
var heart_time = 5000
// tab id
var tabID = null
// 下载文件个数
var fileNum = 0

// popup 点击开始下载
function startWork() {
    console.log('[shopReport] 发送startWork指令')
    sendMessageToContentScript({
        cmd: 'startWork',
        current: 1,
        isSetClicked: false
    }, function (response) {
        if (response && response.type == 'startWork_callback') {
            timer = setInterval(handler, heart_time)
            console.log('[shopReport] 开始执行下载，计时器开始工作')
        }
    })
}

// popup 点击停止工作
function stopWork() {
    clearInterval(timer)
    console.log('[shopReport] 停止下载')
    sendMessageToContentScript({ cmd: 'stopWork' })
    fileNum = 0
    current = 1
    isSetClicked = false
    tabID = null
    timer = null
}

// 循环执行内容
function handler() {
    console.log('[shopReport] 发送download指令')
    sendMessageToContentScript({
        cmd: 'download',
        current: current,
        isSetClicked: isSetClicked
    })
}

function sendMessageToContentScript(message, callback) {
    // 下载文件时会弹出多个新Tab，原先页面可能不会被激活，需要使用旧的tabID进行通信
    if (tabID == null) {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            tabID = tabs.length ? tabs[0].id : null
            chrome.tabs.sendMessage(tabID, message, function (response) {
                if (callback) callback(response);
            });
        });
    } else {
        chrome.tabs.sendMessage(tabID, message, function (response) {
            if (callback) callback(response);
        });
    }
    
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    switch (request.cmd) {
        case 'stopWork':
            stopWork()
            break
        case 'update':
            current = request.current
            isSetClicked = request.isSetClicked
            console.log('[shopReport] 更新状态：' + JSON.stringify(request))
            break
        case 'updateFileNum':
            fileNum += request.fileNum
            break
        case 'getFileNum':
            sendMessageToContentScript({ cmd: 'getFileNum_callback', fileNum: fileNum })
            break
    }
});